﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Localization;
using SinBiota.Model.Business.PersistenceServices.Interfaces;
using SinBiota.Model.Entities;
using Sinbiota.Web.ActionFilters;
using Sinbiota.Web.Models;

namespace Sinbiota.Web.Controllers
{
    public class InstitutionController : BaseController
    {
        private readonly IInstitutionPersistenceServices _institutionPersistenceServices;

        public InstitutionController(IInstitutionPersistenceServices institutionPersistenceServices)
        {
            _institutionPersistenceServices = institutionPersistenceServices;
        }

        //
        // GET: /Institution/
        [ImportMessagesFromTempData]
        [AdminPermission]
        public ActionResult Index()
        {
            return View(_institutionPersistenceServices.FindAll());
        }

        [HttpPost]
        [AdminPermission]
        public ActionResult Index(FormCollection collection)
        {
            return View(_institutionPersistenceServices.FindByNameLike(collection[SearchBoxName]));
        }


        //
        // GET: /Institution/Details/5
        [ImportMessagesFromTempData]
        [AdminPermission]
        public ActionResult Details(int id)
        {
            var institution = _institutionPersistenceServices.FindById(id);
            return institution == null ? View("NotFound") : View(institution);
        }

        //
        // GET: /Institution/Create
        [ImportMessagesFromTempData]
        [AdminPermission]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Institution/Create
        [HttpPost, ExportMessagesToTempData]
        [Authorize]
        public ActionResult Create(Institution institution)
        {
            var newInstitution = new Institution();
            TryUpdateModel(newInstitution);
            if (ModelState.IsValid)
            {
                _institutionPersistenceServices.Save(newInstitution);
                // If it is an AJAX request (Institution may be created by AJAX inside other contexts, like Create Author)
                if (Request != null && Request.IsAjaxRequest()) return Json(JsonMessage.InformationMessage(Messages.OperationCompletedSuccessfully, new { newInstitution.Id }));
                // Normal Action Request:
                SetInformationMessage(Messages.OperationCompletedSuccessfully);
                return RedirectToAction("Index");
            }
            // If it is an AJAX request (Institution may be created by AJAX inside other contexts, like Create Author)
            if (Request.IsAjaxRequest()) throw new Exception(string.Format("{0}: {1}", Messages.ValidationError, ValidationErrorMessage()));
            return View(institution);
        }

        //
        // GET: /Institution/Edit/5
        [ImportMessagesFromTempData]
        [AdminPermission]
        public ActionResult Edit(int id)
        {
            var institution = _institutionPersistenceServices.FindById(id);
            return institution == null ? View("NotFound") : View(institution);
        }

        //
        // POST: /Institution/Edit/5
        [HttpPost, ExportMessagesToTempData]
        [AdminPermission]
        public ActionResult Edit(int id, Institution institution)
        {
            var editInstitution = _institutionPersistenceServices.FindById(id);
            if (editInstitution.Version != institution.Version)
            {
                //Concurrency should be automatically handled by NHibernate, shouldn't it? Am I missing some configuration, or I really have to do it manually?
                ModelState.AddModelError("", Messages.InstitutionController_Edit_Concurrency_problem);
                return View(institution);
            }
            TryUpdateModel(editInstitution);
            if (ModelState.IsValid)
            {
                _institutionPersistenceServices.Update(editInstitution);
                SetInformationMessage(Messages.OperationCompletedSuccessfully);
                return RedirectToAction("Index");
            }
            return View(institution);
        }

        // GET: /Institution/Delete/5
        [ImportMessagesFromTempData]
        [AdminPermission]
        public ActionResult Delete(int id)
        {
            var institution = _institutionPersistenceServices.FindById(id);
            return institution == null ? View("NotFound") : View(institution);
        }

        //
        // POST: /Institution/Delete/5
        [HttpPost, ExportMessagesToTempData]
        [AdminPermission]
        public ActionResult Delete(int id, Institution institution)
        {
            var deleteInstitution = _institutionPersistenceServices.FindById(id);
            if (deleteInstitution == null) return View("NotFound");
            _institutionPersistenceServices.Delete(deleteInstitution);
            SetInformationMessage(Messages.OperationCompletedSuccessfully);
            return RedirectToAction("Index");
        }

        // AJAX: Get all Institutions:
        public JsonResult GetAll()
        {
            var list = _institutionPersistenceServices.FindAll().Select(x => new {x.Id, x.Name}).OrderBy(i => i.Name).ToArray();
            return Json(list);
        }
    }
}
